// @before-stub-for-debug-begin
#include <vector>
#include <string>
#include <queue>
#include "commoncppproblem116.h"

using namespace std;
// @before-stub-for-debug-end

/*
 * @lc app=leetcode.cn id=116 lang=cpp
 *
 * [116] 填充每个节点的下一个右侧节点指针
 */

// @lc code=start
/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
public:
    void connectTwoNode(Node* leftNode,Node* rightNode)
    {
        if(NULL == leftNode ||NULL == rightNode)
        {
            return;
        }

        //处理
        leftNode->next = rightNode;


        //遍历递归
        connectTwoNode(leftNode->left,leftNode->right);
        connectTwoNode(rightNode->left,rightNode->right);

        //处理两个节点相邻的两个左右节点
        connectTwoNode(leftNode->right,rightNode->left);
    }


    Node* connect(Node* root) {
        //因为初始状态下所有next指针均设为NULL,所以不需要管最右侧的节点
        if(NULL == root)
        {
            return root;
        }

        connectTwoNode(root->left,root->right);

        return root;
    }
};
// @lc code=end

